package com.cd.javacxy.module.web.controller;

import com.cd.javacxy.common.annotation.RequireLogin;
import com.cd.javacxy.common.model.entity.CxyAsk;
import com.cd.javacxy.common.model.entity.SessionUser;
import com.cd.javacxy.common.model.enums.DateTimePatternEnum;
import com.cd.javacxy.common.model.enums.ResponseCode;
import com.cd.javacxy.common.model.enums.SolveEnum;
import com.cd.javacxy.common.model.query.AskQuery;
import com.cd.javacxy.common.model.vo.AjaxResponse;
import com.cd.javacxy.common.utils.Constants;
import com.cd.javacxy.common.utils.DateUtil;
import com.cd.javacxy.common.utils.PageResult;
import com.cd.javacxy.exception.BussinessException;
import com.cd.javacxy.module.base.BaseController;
import com.cd.javacxy.module.web.service.CxyAskService;
import com.cd.javacxy.module.web.service.CxyUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * CxyAsk的路由接口服务
 *
 * @author yanghy
 */
@Controller
@RequestMapping("/ask")
@Slf4j
@Validated
public class CxyAskController extends BaseController {

    @Autowired
    private CxyAskService askService;

    @Autowired
    private CxyUserService userService;


    @GetMapping
    public ModelAndView ask(AskQuery askQuery) {
        ModelAndView view = new ModelAndView("ask/ask");
        if (askQuery.getSolveType() == null) {
            askQuery.setSolveType(SolveEnum.WAIT_SOLVE);
        }
        PageResult<CxyAsk> result = this.askService.findAskByPage(askQuery);
        view.addObject("result", result);
        view.addObject("haveSolved", askQuery.getSolveType().getType());
        AskQuery todayAskQuery = new AskQuery();
        view.addObject("totalAsk", this.askService.findCount(todayAskQuery));
        todayAskQuery.setSolveType(SolveEnum.SOLVED);
        view.addObject("totalSolved", this.askService.findCount(todayAskQuery));
        todayAskQuery = new AskQuery();
        Date curDate = new Date();
        todayAskQuery.setStartDate(DateUtil.format(curDate, DateTimePatternEnum.YYYY_MM_DD.getPattern()));
        todayAskQuery.setEndDate(DateUtil.format(curDate, DateTimePatternEnum.YYYY_MM_DD.getPattern()));
        view.addObject("todayAskCount", this.askService.findCount(todayAskQuery));
        todayAskQuery.setSolveType(SolveEnum.SOLVED);
        view.addObject("todaySolvedCount", this.askService.findCount(todayAskQuery));
        view.addObject("topUsers", this.askService.findTopUsers());
        return view;
    }

    @GetMapping("/pre/public")
    public ModelAndView prePublicAsk(HttpSession session) {
        ModelAndView view = new ModelAndView("ask/publicAsk");
        /*SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        if (sessionUser == null) {
            view = new ModelAndView("signin");
            return view;
        }*/
        view.addObject("myCount", userService.findUserByUserId(10000).getMark());
        return view;
    }

    @RequireLogin
    @ResponseBody
    @PostMapping("/publish")
    public AjaxResponse<Integer> publishAsk(HttpSession session, @Validated CxyAsk ask) {
        AjaxResponse<Integer> ajaxResponse = AjaxResponse.<Integer>builder().build();
        this.setUserBaseInfo(CxyAsk.class, ask, session);
        try {
            this.askService.addAsk(ask);
            ajaxResponse.setData(ask.getAskId());
            ajaxResponse.setCode(ResponseCode.SUCCESS.getCode());
        } catch (BussinessException e) {
            ajaxResponse.setErrorMsg(e.getLocalizedMessage());
            ajaxResponse.setCode(ResponseCode.BUSSINESSERROR.getCode());
            log.error("{}提问出错{}", ask.getUserName(), e);
        } catch (Exception e) {
            ajaxResponse.setErrorMsg("服务器出错，提问失败");
            ajaxResponse.setCode(ResponseCode.SERVERERROR.getCode());
            log.error("{}提问出错{}", ask.getUserName(), e);
        }
        return ajaxResponse;
    }

    @GetMapping(value = "/{askId}")
    public ModelAndView askDetail(@PathVariable Integer askId, HttpSession session) {
        ModelAndView view = new ModelAndView("ask/ask_detail");
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        try {
            view.addObject("ask", this.askService.showAsk(askId));
        } catch (BussinessException e) {
            log.error("{}问题加载出错{}", sessionUser.getUserName(), e.getLocalizedMessage());
            view.setViewName("redirect:" + Constants.ERROR_404);
        }
        return view;
    }

    @RequireLogin
    @ResponseBody
    @PostMapping("/accept/answer")
    public AjaxResponse<Object> acceptAnswer(HttpSession session, @Validated AskQuery ask) {
        AjaxResponse<Object> ajaxResponse = AjaxResponse.builder().build();
        this.setUserBaseInfo(CxyAsk.class, ask, session);
        try {
            this.askService.setBestAnswer(ask.getBestAnswerId(), ask.getAskId(), ask.getUserId());
            ajaxResponse.setCode(ResponseCode.SUCCESS.getCode());
        } catch (BussinessException e) {
            ajaxResponse.setErrorMsg(e.getLocalizedMessage());
            ajaxResponse.setCode(ResponseCode.BUSSINESSERROR.getCode());
            log.error("采纳答案出错", e);
        } catch (Exception e) {
            ajaxResponse.setErrorMsg("服务器出错了");
            ajaxResponse.setCode(ResponseCode.SERVERERROR.getCode());
            log.error("采纳答案出错", e);
        }
        return ajaxResponse;
    }

    @ResponseBody
    @GetMapping("/list")
    public AjaxResponse<Object> loadAsk(HttpSession session, AskQuery askQuery) {
        AjaxResponse<Object> ajaxResponse = AjaxResponse.builder().build();
        try {
            PageResult<CxyAsk> pageResult = this.askService.findAskByPage(askQuery);
            ajaxResponse.setData(pageResult);
            ajaxResponse.setCode(ResponseCode.SUCCESS.getCode());
        } catch (Exception e) {
            log.error("加载问答异常", e);
            ajaxResponse.setErrorMsg("加载问答出错");
            ajaxResponse.setCode(ResponseCode.SERVERERROR.getCode());
        }
        return ajaxResponse;
    }
}
